import os
from dotenv import load_dotenv
from tortoise.contrib.fastapi import register_tortoise
from tortoise import Tortoise


# 加载 .env 文件（自动查找）
load_dotenv(override=True)


# 关于tortoise的配置
TORTOISE_ORM = {
    "connections": {
        "default": {
            "engine": "tortoise.backends.mysql",
            "credentials": {
                "host": os.getenv("DB_HOST", "localhost"),
                "port": int(os.getenv("DB_PORT", "3306")),
                "user": os.getenv("DB_USER", "root"),
                "password": os.getenv("DB_PASSWORD", "88888888"),
                "database": os.getenv("DB_NAME", "fast-nav"),
                "charset": "utf8mb4",
            }
        }
    },
    "apps": {
        "models": {
            "models": [
                "aerich.models", 
                "app.modules.users.models", 
                "app.modules.permissions.models", 
                "app.modules.roles.models",
                "app.modules.system.models",
                "app.modules.logs.models",
                "app.modules.files.models"
            ],
            "default_connection": "default",
        }
    }
}

# 注册mysql数据库
async def register_mysql(app):
    # 初始化数据库连接, 如果在main中直接注册orm模型，则不需要这一步
    await Tortoise.init(config=TORTOISE_ORM)
    # 注册ORM模型
    register_tortoise(
        app,
        config=TORTOISE_ORM,
        generate_schemas=False,  # 我们手动生成数据库表
        add_exception_handlers=True,
    )